package dtaskboard.client.project.dialog;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import dtaskboard.client.Constants;
import dtaskboard.client.DialogUtil;
import dtaskboard.client.service.ProjectService;
import dtaskboard.client.service.ProjectServiceAsync;

public class EditProjectDialog extends DialogBox {

  private final TextBox projectHours;
  private final TextBox projectSprints;
  private final String projectName;

  public EditProjectDialog(String projectName) {
    this.projectHours = new TextBox();
    this.projectSprints = new TextBox();
    this.projectName = projectName;

    Label projectHoursLabel = new Label("Horas estimadas no projeto");
    Label projectSprintsLabel = new Label("Sprints estimados no projeto");
    Panel panel = new VerticalPanel();

    panel.add(projectHoursLabel);
    panel.add(this.projectHours);
    panel.add(projectSprintsLabel);
    panel.add(this.projectSprints);
    panel.add(new EditProjectSubmitButton());

    super.setAnimationEnabled(true);
    super.setAutoHideEnabled(true);
    super.setHTML("Editar");
    super.setGlassEnabled(true);
    super.setModal(true);
    super.setWidget(panel);
    super.setVisible(true);
  }

  class EditProjectSubmitButton extends Button {
    public EditProjectSubmitButton() {
      this.setText("Salvar alterações");
      this.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
          ProjectServiceAsync projectService = GWT.create(ProjectService.class);
          String sessionId = Cookies.getCookie(Constants.sessionIdCookie);
          final EditProjectDialog epd = EditProjectDialog.this;
          projectService.updateProject(EditProjectDialog.this.projectName,
              EditProjectDialog.this.projectHours.getText(),
              EditProjectDialog.this.projectSprints.getText(), sessionId,
              new AsyncCallback<Void>() {

                @Override
                public void onFailure(Throwable caught) {
                  DialogUtil.closableDialog("Erro",
                      "Nao foi possível alterar o projeto.");
                }

                @Override
                public void onSuccess(Void result) {
                  DialogUtil.closableDialog("Edição de projeto",
                      "Projeto alterado com sucesso");
                  epd.hide();
                }

              });
        }
      });
    }
  }

}
